package com.lagou.worker.controller;

import com.lagou.worker.controller.service.MailService;
import com.lagou.worker.model.LagouAuthCode;
import com.lagou.worker.service.LagouAuthCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * @ClassName CodeController
 * @Description TODO
 * @Author xsq
 * @Date 2020/7/28 16:20
 **/
@RestController
@RequestMapping("/code")
@Slf4j
public class CodeController {

    @Autowired
    private LagouAuthCodeService lagouAuthCodeService;

    @Autowired
    private MailService mailService;

    @GetMapping("/create/{email}")
    public ResponseEntity getLoginUrl(@PathVariable("email") String email) {
        String code = getValidationCode();
        //把验证码发送到邮箱
        ResponseEntity<Boolean> responseEntity = mailService.sendEmail(email, code);
        if (responseEntity.getBody()) {
            lagouAuthCodeService.setEmailCode(email, code);
            log.info("-------验证码发送成功-------：" + code);
            return ResponseEntity.ok(true);
        }
        return ResponseEntity.badRequest().body("验证码发送失败");
    }


    /**
     * 获取6位随机验证码
     *
     * @return
     */
    private static String getValidationCode() {
        return String.valueOf((new Random().nextInt(899999) + 100000));
    }

    @GetMapping("/validate/{email}/{code}")
    public ResponseEntity validate(@PathVariable("email") String email,
                                   @PathVariable("code") String code) {
        //验证码验证
        LagouAuthCode lagouAuthCode = lagouAuthCodeService.validate(email);
        Long time = (System.currentTimeMillis() - lagouAuthCode.getExpiretime().getTime()) / 1000;
        if (lagouAuthCode == null) {
            return ResponseEntity.ok(3);
        }
        //超过10分钟验证码无效
        if (time > 10 * 60) {
            return ResponseEntity.ok(2);
        }
        if (code.equals(lagouAuthCode.getCode())) {
            return ResponseEntity.ok(0);
        } else {
            return ResponseEntity.ok(1);
        }

    }

}
